package com.itshizhan.itjidancideveloper.controller.ucenter

import com.itshizhan.itjidancideveloper.dao.ucenter.WordRootDao
import com.itshizhan.itjidancideveloper.models.WordRoot
import com.itshizhan.itjidancideveloper.response.CodeMsgEnum
import com.itshizhan.itjidancideveloper.response.Response
import org.springframework.web.bind.annotation.*

@RestController()
@RequestMapping("/ucenter/root")
class WordRootController(private val wordRootDao: WordRootDao) {

  @GetMapping("/search")
  fun getByKeyword(@RequestParam("q") keyword: String): Response<MutableList<WordRoot>> {
    if (keyword.length < 2) {
      return Response.code(CodeMsgEnum.ERROR_PARAMETER)
    }
    return Response.success(wordRootDao.findByRootNameLike("%$keyword%"))
  }

  @GetMapping("/detail")
  fun getDetailById(@RequestParam("id") id: Long): Response<WordRoot> {
    val root = wordRootDao.findById(id).orElse(null)
    return Response.success(root)
  }

  @PostMapping("/save")
  fun save(@RequestBody wordRoot: WordRoot): Response<WordRoot> {
    val dbRoot = wordRootDao.findById(wordRoot.id).orElse(null)
    if (dbRoot!=null){
      dbRoot.memoryMd = wordRoot.memoryMd;
      dbRoot.memoryHtml = wordRoot.memoryHtml;
      val root = wordRootDao.save(dbRoot)
      return Response.success(root)
    }
    return Response.fail(CodeMsgEnum.SAVE_FAIL.msg)

  }
}